package com.dhcc.test.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dhcc.test.entityBinding.User;

/**
 * @description ：Filter过滤器之资源权限控制(访问资源权限控制器)
 * @date ：2016年11月30日 下午2:22:13
 * @author ：WangYG
 */
public class ResourceAccessControlFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 判断如果是index.jspx 放行
        String uri = request.getRequestURI();
        uri = uri.substring(uri.lastIndexOf("/") + 1);
        // System.out.println("当前请求的路径: " + uri);
        System.out.println("用户要访问的URI资源是：" + ">>>>"+ uri );
        if ("".equals(uri) || "index.jsp".equals(uri) || "index.jspx".equals(uri) || "login.jsp".equals(uri) ||  "login.do".equals(uri) || uri.endsWith("png") || uri.endsWith("jpg")) {
            // 所有人都能请求到的URI，放行
            filterChain.doFilter(request, response);
        } else {// 下面是判断是否有session，也就是用户是否已登录状态
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("USER_IN_SESSION");
            if (user == null) {
                System.out.println("URI:" + uri + ">>>>访问被拒绝！");
                session.setAttribute("AccessError", "未登陆，访问被拒绝！");
                response.sendRedirect("index.jsp?errorCode=0002");
            } else {
                filterChain.doFilter(request, response);
            }
        }

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}
